

package cn.shengchao.examstart.medialibrary.ohs.local.appservice;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.base.event.CourseUploadEvent;
import cn.shengchao.examstar.ai.infrastructure.external.ai.util.AIUtil;
import cn.shengchao.examstar.ai.infrastructure.external.ai.util.JsonToSubtitle;
import cn.shengchao.examstar.ai.infrastructure.external.ai.util.VideoJsonToText;
import cn.shengchao.examstar.ai.infrastructure.external.ai.util.entity.AiVideoResult;
import cn.shengchao.examstart.medialibrary.acl.ports.repositories.IFileRepository;
import cn.shengchao.examstart.medialibrary.infrastructure.dao.po.TFileTask;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.jetbrains.annotations.Nullable;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class VideoService {

    @Autowired
    private AIUtil aiUtil;

    @Autowired
    private IFileRepository iFileRepository;

    private final ChatClient chatClient;

    public VideoService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public AiVideoResult getTaskResult(Long fileId) throws ExecutionException, InterruptedException {
        TFileTask task = iFileRepository.getFileTaskId(fileId);
        if (task == null) {
            return new AiVideoResult();
        }
        return aiUtil.getTaskResult(task.getTaskId());
    }

    @EventListener
    public void handleCourseUploadEvent(CourseUploadEvent courseUploadEvent) throws Exception {
        CourseUploadEvent.CourseUploadMessage courseUploadMessage = (CourseUploadEvent.CourseUploadMessage) courseUploadEvent
                .getSource();
        extracted(courseUploadMessage.getVideoUrl());
    }

    private void extracted(String videoUrl) throws Exception {
        //根据视频地址查询文件id
        Long fileId = iFileRepository.getFileByUrl(videoUrl);
        if (fileId != null) {
            //查看是否有任务id
            TFileTask tFileTask = iFileRepository.getFileTaskId(fileId);
            if (tFileTask == null || StrUtil.isEmpty(tFileTask.getTaskId())) {
                //创建ai任务
                if (!videoUrl.contains("?")) {
                    videoUrl = videoUrl + "?Authorization=Bearer " + StpUtil.getTokenValue();
                }
                String taskId = aiUtil.createTaskAiVideo(videoUrl);
                //更新文件
                iFileRepository.updateFileTaskId(fileId, taskId);
            }
        }
    }

    public AiVideoResult getTaskResult(String videoUrl) throws Exception {
        Long fileId = iFileRepository.getFileByUrl(videoUrl);
        if (fileId != null) {
            //查看是否有任务id
            TFileTask task = iFileRepository.getFileTaskId(fileId);
            if (task != null && StrUtil.isNotEmpty(task.getTaskId())) {
                return getAiVideoResult(videoUrl, task);
            }
        }
        extracted(videoUrl);
        return new AiVideoResult();
    }

    @Nullable
    private AiVideoResult getAiVideoResult(String videoUrl, TFileTask task) throws Exception {
        AiVideoResult aiVideoResult = aiUtil.getTaskResult(task.getTaskId());
        if (aiVideoResult == null) {
            iFileRepository.delete(task.getId());
            extracted(videoUrl);
            return null;
        }
        //如果视频没有文字
        if (StrUtil.isEmpty(task.getVideoText())) {
            DashScopeApi api = new DashScopeApi("sk-1d49f48a8b0f4bad95ce18791212d22c");
            DashScopeChatOptions dashScopeChatOptions = new DashScopeChatOptions();
            dashScopeChatOptions.setModel("qwen-max-latest");
            ChatModel chatModel = new DashScopeChatModel(api, dashScopeChatOptions);
            String videoText = VideoJsonToText.extractText(aiVideoResult.getTranscription()
                    .getJSONObject("Transcription")
                    .getJSONArray("Paragraphs"));
            CompletableFuture<String> caption = CompletableFuture.supplyAsync(() -> JsonToSubtitle.convertToJsonSubtitle(aiVideoResult.getTranscription()
                    .getJSONObject("Transcription")
                    .getJSONArray("Paragraphs")));
            try {
                CompletableFuture<String> briefly = CompletableFuture.supplyAsync(() -> ChatClient.create(chatModel)
                        .prompt()
                        .system("你是一个文稿优化师，你有超过10年的数据整理经验。现在需要你把我的文稿优化，去除语气词，自我介绍,不要过度精简，也不要啰嗦")
                        .user(videoText)
                        .call()
                        .content());
                task.setBriefly(briefly.get());
            } catch (Exception e) {
                task.setBriefly(videoText);
            }
            task.setVideoText(videoText);
            task.setCaption(caption.get());
            iFileRepository.updateFileTaskId(task);
        }
        aiVideoResult.setVideoText(task.getVideoText());
        aiVideoResult.setBriefly(task.getBriefly());
        return aiVideoResult;
    }
}
